import React, { memo, useRef, useEffect } from 'react';
import * as echarts from 'echarts/core';
import { TooltipComponent, GridComponent } from 'echarts/components';
import { BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

import './style.less';

echarts.use([TooltipComponent, GridComponent, BarChart, CanvasRenderer]);

export default memo(function MyBarEchart(props) {
  const chartRef = useRef();

  useEffect(() => {
    const myChart = echarts.init(chartRef.current);
    const optionList = [];
    const dataList = [];
    if (props.dataList[0]) {
      for (let item of props.dataList) {
        optionList.push(item.name);
        dataList.push(item.goodsFavor);
      }
    }
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: optionList,
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: 'Direct',
          type: 'bar',
          barWidth: '60%',
          data: dataList,
        },
      ],
    };
    myChart.setOption(option);
  }, [props]);

  return <div className="my-bar-echart" ref={chartRef}></div>;
});
